#!/usr/bin/env python
'''
Copyright (C) 2006, 2007 Aaron Spike, aaron@ekips.org

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
'''

import random, re, string
import pygame
from pygame.locals import *
from activity import Activity

class KeyActivity(Activity):
    def __init__(self, screen):
        Activity.__init__(self, screen)
        self.sounds = {}
        self.sound = None
        self.kp_dict = {K_KP0:"0",K_KP1:"1",K_KP2:"2",K_KP3:"3",K_KP4:"4",K_KP5:"5",K_KP6:"6",K_KP7:"7",K_KP8:"8",K_KP9:"9"}
        self.kp_set = set(self.kp_dict.keys())
        self.test = re.compile('^[0-9A-Za-z]$')
        self.change = self.noop
    def noop(self):
        pass
    def handle_events(self):
        self.sound = None
        self.change = self.noop
        
        event = pygame.event.wait()
        if event.type == QUIT:
            self.quit = True
            return
        elif event.type == KEYUP:
            self.changed = True
            if event.key == K_ESCAPE:
                self.quit = True
                return
            else:
                if event.key in self.kp_set:
                    key = self.kp_dict[event.key]
                else:
                    key = pygame.key.name(event.key)
    
                if self.test.match(key):
                    self.sound = self.sounds.setdefault(key.lower(),self.load_sound('%s.ogg' % key))
                    if KMOD_CAPS & event.mod:
                        key = key.upper()
                    if KMOD_NUM & event.mod and key in string.ascii_letters:
                        key = key.upper() + key.lower()
                    if pygame.font:
                        font = pygame.font.Font(None, int(self.background.get_height()*0.9))
                        text = font.render(key, 1, (255,255,255))
                        textpos = (self.center[0]-int(text.get_width()/2),self.center[1]-int(text.get_height()/2))
                        def op():
                            self.screen.blit(text, textpos)
                        self.change = op
    def on_change(self):
        if self.change:
            self.change()
        if self.sound:
            self.sound.play()